package com.tanhua.manage.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.manage.domain.UserFreezing;
import com.tanhua.manage.mapper.UserFreezingMapper;
import com.tanhua.manage.vo.UserFreezingVo;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VideoApi videoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;

    @Autowired(required = false)
    private UserFreezingMapper userFreezingMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //冻结登录
    private static final String freezingLogin = "userFreezing_login_";

    //冻结发言
    private static final String freezingComment = "userFreezing_comment_";

    //冻结发布动态
    private static final String freezingPublish = "userFreezing_publish_";

    public ResponseEntity<Object> findByPage(Integer page, Integer pagesize) {
        Page<UserInfo> pageInfo = userInfoApi.findByPage(page,pagesize);
        PageResult pageResult = new PageResult(page,pagesize,(int)pageInfo.getTotal(),pageInfo.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    //用户基本信息
    public ResponseEntity<Object> findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }


//    视频记录翻页
    public ResponseEntity<Object> findVideosList(Integer page, Integer pagesize, long uid) {
       PageResult pageResult =  videoApi.findPageByUid(page,pagesize,uid);
        //2. 得到视频列表List<Video>
        List<Video> videoList = (List<Video>) pageResult.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();
        //3. 遍历视频列表，把Video的数据转换为VideoVo，添加到集合
        if(videoList!=null) {
            for (Video video : videoList) {
                VideoVo videoVo = new VideoVo();
                //查询视频上传人的用户信息
                UserInfo userInfo = userInfoApi.findById(video.getUserId());
                if(userInfo!=null) {
                    BeanUtils.copyProperties(userInfo, videoVo);
                }
                BeanUtils.copyProperties(video,videoVo);
                videoVo.setId(video.getId().toString());
                videoVo.setCover(video.getPicUrl()); //视频的封面图片
                videoVo.setSignature(video.getText()); //视频的签名，标题
                videoVoList.add(videoVo);
            }
        }
        //4. 修改pageResult存储的数据
        pageResult.setItems(videoVoList);

        //目标： 存储VideoVo对象
        return ResponseEntity.ok(pageResult);
    }

    //查询用户的朋友圈
    public ResponseEntity<Object> findMovementsList(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult = publishApi.queryMyPublishList(page, pagesize, uid);
        //3. 得到分页的对象Items, List<Publish>
        List<Publish> publishList= (List<Publish>) pageResult.getItems();

        //4. 遍历所有的Publish，把publish构建为MovementsVo
        List<MovementsVo> voList = new ArrayList<>();
        if(publishList!=null){
            for (Publish publish : publishList) {
                MovementsVo vo  = new MovementsVo();
                //查询朋友圈发布人的用户信息
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if(userInfo!=null){
                    BeanUtils.copyProperties(userInfo,vo);
                    if(userInfo.getTags()!=null){
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                //把publish信息转义到movementsVo
                BeanUtils.copyProperties(publish,vo);
                //id
                vo.setId(publish.getId().toString());
                //图片
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                //距离
                vo.setDistance("50米");
                //发布时间 ,发布朋友圈距离今天的时间
                vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()),"yyyy-MM-dd HH:mm:ss"));
                voList.add(vo);
            }
        }


        //5. 修改PageResult对象存储的内容
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    //根据id查询动态
    public ResponseEntity<Object> findMovementsById(String publishId) {
        Publish publish = publishApi.findById(publishId);
        MovementsVo vo  = new MovementsVo();
        //查询朋友圈发布人的用户信息
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        if(userInfo!=null){
            BeanUtils.copyProperties(userInfo,vo);
            if(userInfo.getTags()!=null){
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        //把publish信息转义到movementsVo
        BeanUtils.copyProperties(publish,vo);
        //id
        vo.setId(publish.getId().toString());
        //图片
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        //距离
        vo.setDistance("50米");
        //发布时间 ,发布朋友圈距离今天的时间
        vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()),"yyyy-MM-dd HH:mm:ss"));
        return ResponseEntity.ok(vo);

    }

    //根据动态id查询动态的评论列表
    public ResponseEntity<Object> findCommentsById(String publishId, Integer page, Integer pagesize) {
        PageResult pageResult = commentApi.queryCommentsList(publishId, page, pagesize);

        //得到pageResult的Items
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
        List<CommentVo> voList = new ArrayList<>();
        //2. 把Comment对象转换为CommentVo对象
        if(!commentList.isEmpty()) {
            for (Comment comment : commentList) {
                CommentVo commentVo = new CommentVo();
                commentVo.setId(comment.getId().toString());
                //查找评论人的用户信息
                UserInfo userInfo = userInfoApi.findById(comment.getUserId());
                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm:ss"));
                commentVo.setLikeCount(0);
                commentVo.setHasLiked(0);
                voList.add(commentVo);
            }
        }
        //3. 修改pageResult存储的内容
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    //动态审核翻页展示
    public ResponseEntity<Object> dynamicReview(Integer page, Integer pagesize, String state) {
        PageResult pageResult = publishApi.dynamicReview(page,pagesize,state);
        //3. 得到分页的对象Items, List<Publish>
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        //4. 遍历所有的Publish，把publish构建为MovementsVo
        List<MovementsVo> voList = new ArrayList<>();
        if (publishList != null) {
            for (Publish publish : publishList) {
                MovementsVo vo = new MovementsVo();
                //查询朋友圈发布人的用户信息
                UserInfo userInfo = userInfoApi.findById(publish.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }
                //把publish信息转义到movementsVo
                BeanUtils.copyProperties(publish, vo);
                //id
                vo.setId(publish.getId().toString());
                //图片
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));
                //发布时间 ,发布朋友圈距离今天的时间
                vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()), "yyyy-MM-dd HH:mm:ss"));
                voList.add(vo);
            }
        }
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }

    //动态通过
    public ResponseEntity<Object> cheakPass(String[] uid) {
        publishApi.pass(uid);
        String message="操作成功";
        return ResponseEntity.ok(message);
    }

    //动态拒绝
    public ResponseEntity<Object> cheakReject(String[] uid) {
        publishApi.reject(uid);
        String message="操作成功";
        return ResponseEntity.ok(message);
    }

    /**
     * 接口名称：用户冻结操作
     *
     * @param userFreezingVo
     * @return String 操作成功
     */
    public ResponseEntity<Object> freezingUser(UserFreezingVo userFreezingVo) {
        //得到被冻结的用户id
        Integer userId = userFreezingVo.getUserId();

        //封装用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("2");

        //更改userInfo用户冻结情况status
        userInfoApi.update(userInfo);

        //将用户的冻结信息保存到user_freezing表中
        UserFreezing userFreezing = new UserFreezing();

        BeanUtils.copyProperties(userFreezingVo,userFreezing);
        userFreezing.setCreated(new Date());
        userFreezing.setUpdated(new Date());

        userFreezingMapper.insert(userFreezing);

        //判断冻结天数 1为冻结3天，2为冻结7天，3为永久冻结
        if (userFreezingVo.getFreezingTime() == 1){

            //判断冻结范围 1为冻结登录，2为冻结发言，3为冻结发布动态
            if(userFreezingVo.getFreezingRange() == 1){

                //将redis的key保存时间设置为3天
                redisTemplate.opsForValue().set(freezingLogin + userId, userFreezingVo.getFreezingTime().toString(), 60, TimeUnit.SECONDS);

            }else if(userFreezingVo.getFreezingRange() == 2){
                redisTemplate.opsForValue().set(freezingComment + userId, userFreezingVo.getFreezingTime().toString(), 3, TimeUnit.DAYS);

            }else if(userFreezingVo.getFreezingRange() == 3){
                redisTemplate.opsForValue().set(freezingPublish + userId, userFreezingVo.getFreezingTime().toString(), 3, TimeUnit.DAYS);
            }

            //判断冻结天数 1为冻结3天，2为冻结7天，3为永久冻结
        }else if(userFreezingVo.getFreezingTime() == 2){

            //判断冻结范围 1为冻结登录，2为冻结发言，3为冻结发布动态
            if(userFreezingVo.getFreezingRange() == 1){

                //将redis的key保存时间设置为7天
                redisTemplate.opsForValue().set(freezingLogin + userId, userFreezingVo.getFreezingTime().toString(), 7, TimeUnit.DAYS);

            }else if(userFreezingVo.getFreezingRange() == 2){
                redisTemplate.opsForValue().set(freezingComment + userId, userFreezingVo.getFreezingTime().toString(), 7, TimeUnit.DAYS);

            }else if(userFreezingVo.getFreezingRange() == 3){
                redisTemplate.opsForValue().set(freezingPublish + userId, userFreezingVo.getFreezingTime().toString(), 7, TimeUnit.DAYS);
            }

            //判断冻结天数 1为冻结3天，2为冻结7天，3为永久冻结
        }else if(userFreezingVo.getFreezingTime() == 3){

            //判断冻结范围 1为冻结登录，2为冻结发言，3为冻结发布动态
            if(userFreezingVo.getFreezingRange() == 1){

                //直接将数据存入redis中
                redisTemplate.opsForValue().set(freezingLogin + userId, userFreezingVo.getFreezingTime().toString());

            }else if(userFreezingVo.getFreezingRange() == 2){
                redisTemplate.opsForValue().set(freezingComment + userId, userFreezingVo.getFreezingTime().toString());

            }else if(userFreezingVo.getFreezingRange() == 3){
                redisTemplate.opsForValue().set(freezingPublish + userId, userFreezingVo.getFreezingTime().toString());
            }
        }

        //返回数据
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return ResponseEntity.ok(map);
    }

    /**
     * 接口名称：用户解冻操作
     * @param userId 用户id
     * @param reasonsForThawing 解冻原因
     * @return String 操作成功
     */
    public ResponseEntity<Object> unFreezingUser(Integer userId, String reasonsForThawing) {
        //根据userId 更改userInfo里的status信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);

        //更改tb_user_freezing表里的数据
        UserFreezing userFreezing = new UserFreezing();
        userFreezing.setUserId(userId);
        userFreezing.setReasonsForFreezing(reasonsForThawing);
        userFreezing.setIsFreezing(2);
        userFreezing.setUpdated(new Date());

        //查询id_freezing 不等于2 的数据 并修改
        QueryWrapper<UserFreezing> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("is_freezing", 2).eq("user_id",userId);
        userFreezingMapper.update(userFreezing, queryWrapper);

        //删除redis中的数据
        redisTemplate.delete(freezingLogin + userId);
        redisTemplate.delete(freezingPublish + userId);
        redisTemplate.delete(freezingComment + userId);

        //返回数据
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return ResponseEntity.ok(map);
    }



}
